package com.atguigu.gmall.gateway.filter;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * @author: atguigu
 * @create: 2023-07-24 11:41
 */
@Configuration
public class CorsFilterConfig {


    /**
     * 配置CORS过滤配置：配置跨域规则
     *
     * @return
     */
    @Bean
    public CorsWebFilter corsWebFilter() {
        // 1.创建跨域规则
        CorsConfiguration configuration = new CorsConfiguration();
        //1.1 指定允许哪些域名跨域访问
        configuration.addAllowedOrigin("*");

        //1.2 指定运行哪些额外请求头来进行访问（要求携带哪些特殊请求头才能跨域访问）
        configuration.addAllowedHeader("*");

        //1.3 指定运行哪些http方式访问
        configuration.addAllowedMethod("*");

        //1.4 指定是否携带Cookie
        configuration.setAllowCredentials(true);

        //1.5 设置预检请求有效期
        configuration.setMaxAge(3600L);

        //2.创建CORS配置对象
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        //
        source.registerCorsConfiguration("/**", configuration);
        //3. 创建跨域过滤器对象
        return new CorsWebFilter(source);
    }


}
